<?php
namespace fast;
use Yansongda\Pay\Pay;
use think\Config;
use app\common\model\Order;
use think\Exception;
use think\Db;
/**
 * 支付 会员,私董会,实战,活动
 * type level,group,adviser,special,
 */
class Payment {
  

    public static function alipay($id,$type,$price,$userid,$json_data = ''){
        Db::startTrans();
        try {
            $data = '';
            switch ($type) {
                case 'level':
                    $data = '购买会员服务';
                    break;
                case 'group':
                    $data = '申请私董会成员';
                    break;
                case 'adviser':
                    $data = '参加实战活动';
                    break;
                case 'special':
                    $data = '参加线下活动';
                    break;
            }
            $order = new Order();
            $order->table_id = $id;
            $order->out_trade_no = $type.date('ymdHis').mt_rand(1000, 9999).substr(time(), '3', '8');
            $order->type = $type;
            $order->json_data = $json_data;
            $order->price = $price;
            $order->pay_type = 'alipay';
            $order->content = $data;
            $order->user_id = $userid;
            $order->pay_status = 0;
            $order->save();
            self::main();
            $result = Pay::alipay()->scan([
                'out_trade_no' => $order->out_trade_no,
                'total_amount' => $order->price,
                'subject' => $order->content,
            ]);
            Db::commit();
            return ['url'=>request()->domain().'/qrcode/build?text='.urlencode($result['qr_code']),'order'=>$order];
        } catch ( Exception $e) {
            Db::rollback();
            return false;
        }
        
    }
    public static function wechat($id,$type,$price,$userid,$json_data = ''){
        Db::startTrans();
        try {
            $data = '';
            switch ($type) {
                case 'level':
                    $data = '购买会员服务';
                    break;
                case 'group':
                    $data = '申请私董会成员';
                    break;
                case 'adviser':
                    $data = '参加实战活动';
                    break;
                case 'special':
                    $data = '参加线下活动';
                    break;
            }
            $order = new Order();
            $order->table_id = $id;
            $order->out_trade_no = $type.date('ymdHis').mt_rand(1000, 9999).substr(time(), '3', '8');
            $order->type = $type;
            $order->price = $price;
            $order->json_data = $json_data;
            $order->pay_type = 'wechat';
            $order->content = $data;
            $order->user_id = $userid;
            $order->pay_status = 0;
            $order->save();
            self::main();
            $result = Pay::wechat()->scan([
                'out_trade_no' => $order->out_trade_no,
                'description' => $order->content,
                'amount' => [
                    'total' => intval($order->price * 100),
                ],
            ]);
            Db::commit();
            return ['url'=>request()->domain().'/qrcode/build?text='.urlencode($result['code_url']),'order'=>$order];
        } catch ( Exception $e) {
            Db::rollback();
            return false;
        }
    }
    public static function query($out_trade_no,$return=false){
        $order = Order::where('out_trade_no',$out_trade_no)->find();
        if($order['pay_status'] == 1){
            return true;
        }
        $orderparams = [
            'out_trade_no' => $order->out_trade_no,
        ];
        self::main();
        $result=null;
        if($order['pay_type'] == 'wechat'){
            $result = Pay::wechat()->query($orderparams);
            /**"out_trade_no" : "1217752501201407033233368018",
                 "transaction_id" : "1217752501201407033233368018",
                "trade_type" : "APP",
                "trade_state" : "SUCCESS",
                "trade_state_desc" : "支付成功",
                "bank_type" : "CMC",
                "attach" : "自定义数据",
                "success_time" : "2018-06-08T10:34:56+08:00",
                "payer" : {
                    "openid" : "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o\t"
                },
                "amount" : {
                    "total" : 100, */
            if($result['trade_state'] == 'success'){
                $order->pay_status = 1;
                $order->trade_no = $result['transaction_id'];
                $order->pay_time = date('Y-m-d H:i:s');
                $order->save();
                return true;
            }else{
                return false;   
            }
        }else{
            /** "trade_no": "2013112011001004330000121536",
                *"out_trade_no": "6823789339978248",
                *"buyer_logon_id": "159****5620",
                *"trade_status": "TRADE_SUCCESS",
                *"total_amount": "88.88",*/
            $result = Pay::alipay()->query($orderparams);
            if($result['trade_status'] == 'TRADE_SUCCESS'){
                $order->pay_status = 1;
                $order->trade_no = $result['trade_no'];
                $order->save();
                return true;
            }else{
                return false;
            }
            
        }
   
    }
    public static function return($out_trade_no){
       $result = self::query($out_trade_no);
    }
    public static function notify($out_trade_no){
        $result = self::query($out_trade_no,true);

    }
    public static function main(){
        $site = Config::get('site');
        $config = [
            'alipay' => [
                'default' => [
                    'app_id' => '2021005116685378',
                    'app_secret_cert' => 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCQW+A2qL3w7JZDouFxSe5TynnxtwmzRWkLstBCkAAD17G5rah9f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kQDHC/5SvxOEdrdG6gJpPt7UdaRGNq6br/bgk9Wg7MJOD5OVcznotB0sDOF3ICUUmOteUnIYvdB3MjMr8QuZGz7wcwqUslvybTK6/xNu7fVAoGAMaHArNKitAZq+fqz02bj0vEUK73iHqgMD++AxihJZ2xvkC6Y17RrDb0TfHj+rSNq4FwnECYOGOEHLDzi/UXFdIo1+xb93VmUuM6IplvIIoCgVia3P6imhQ6xb84pZaRnBQDYowy1/T0kjuErwv2AS8MWDEteV/1uKoT8bUPBAosCgYB1reI9gdnGYDpA4d2QFiyUzZUiwS5liIf7UeuauI57icJOIGp4lHzp7rIFbS9TOuzLiIaknDsfzvkOWIDSc6QCUzeIHrb5B9g0t4InB5/TEuuUTmWQvJPCv1PCJHpcEdg1Z2uT0pyogeGoACzGDHE1SA8dVXA8uLtbzTvcc85KCQ==',
                    'app_public_cert_path' => EXTEND_PATH.'appCertPublicKey_2021005116685378.crt',
                    'alipay_public_cert_path' => EXTEND_PATH.'alipayCertPublicKey_RSA2.crt',
                    'alipay_root_cert_path' => EXTEND_PATH.'alipayRootCert.crt',
                    'return_url' => request()->domain().'/alipay/return',
                    'notify_url' => request()->domain().'/alipay/notify',
                    'mode' => Pay::MODE_NORMAL,
                ]
            ],
            
            'wechat' => [
                'default' => [
                    'mch_id' => $site['mch_id'],
                    'mch_secret_key' => $site['mch_secret_key'],
                    'mch_secret_cert' => EXTEND_PATH.'apiclient_key.pem',
                    'mch_public_cert_path' => EXTEND_PATH.'apiclient_cert.pem',
                    'notify_url' => request()->domain().'/wechat/notify',
                    'mp_app_id' => 'wx3e8e3aa866a1d180',
                    'wechat_public_cert_path' => [
                        'PUB_KEY_ID_0117045317302025032600337900002858' => EXTEND_PATH.'pub_key.pem',
                    ],
                    // 「选填」默认为正常模式。可选为： MODE_NORMAL, MODE_SERVICE
                    'mode' => Pay::MODE_NORMAL,
                ]
            ]
        ];    
        Pay::config($config);
    }
}